package top.hepingan.java.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import top.hepingan.java.common.Result;
import top.hepingan.java.entity.User;
import top.hepingan.java.mapper.UserMapper;
import top.hepingan.java.service.IUserService;
import top.hepingan.java.utils.UserUtils;

import java.time.LocalDateTime;

@RequestMapping("/user")
@RestController
@Slf4j
@RequiredArgsConstructor
public class UserController {


    private final UserMapper userMapper;

    private final IUserService userService;

    /**
     * 登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        User u = userMapper.selectOne(new QueryWrapper<User>().lambda()
                .eq(User::getUsername, user.getUsername())
                .eq(User::getPassword, user.getPassword()));
        if (u != null){
            StpUtil.login(u.getId());
            return Result.data(StpUtil.getTokenInfo());
        }else {
            return Result.error("登录失败");
        }
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody User user){
        User u = userMapper.selectOne(new QueryWrapper<User>().lambda()
                .eq(User::getUsername, user.getUsername()));

        if (u != null){
            return Result.error("用户名已存在");
        }else {
            user.setCreatedTime(LocalDateTime.now());
            userService.save(user);
            return Result.ok();
        }
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody User user){
        User u = userMapper.selectOne(new QueryWrapper<User>().lambda()
                .eq(User::getId, UserUtils.getCurrentLoginId()));
        if (u != null){
            u.setUsername(user.getUsername());
            u.setPassword(user.getPassword());
            u.setPhone(user.getPhone());
            userService.updateById(u);
           return Result.ok();
        }else {
            return Result.error("用户不存在");
        }
    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/getUserInfo")
    public Result getUserInfo(){
        User u = userMapper.selectById(UserUtils.getCurrentLoginId());
        return Result.data(u);
    }






}
